package com.example.roleplay.controller;

import com.example.roleplay.service.tts.TTSClient;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

/**
 * TTS（语音合成）API控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/tts")
@RequiredArgsConstructor

public class TTSController {

    private final TTSClient ttsClient;

    @GetMapping(produces = "audio/mpeg")

    public ResponseEntity<byte[]> synthesize(
            @RequestParam String text,
            @RequestParam(required = false) String voice,
            @RequestParam(defaultValue = "zh-CN") String language) {
        
        try {
            if (text == null || text.trim().isEmpty()) {
                return ResponseEntity.badRequest().build();
            }

            // 限制文本长度
            if (text.length() > 1000) {
                text = text.substring(0, 1000);
            }

            // 如果没有指定声音，使用默认声音
            if (voice == null || voice.trim().isEmpty()) {
                voice = ttsClient.getDefaultVoice(language);
            }

            log.info("开始TTS合成 - 文本长度: {}, 声音: {}, 语言: {}", text.length(), voice, language);

            byte[] audioData = ttsClient.synthesize(text, voice, language);

            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.valueOf("audio/mpeg"));
            headers.setContentLength(audioData.length);
            headers.set("Content-Disposition", "inline; filename=\"speech.mp3\"");

            log.info("TTS合成完成 - 音频大小: {} bytes", audioData.length);

            return ResponseEntity.ok()
                    .headers(headers)
                    .body(audioData);

        } catch (Exception e) {
            log.error("TTS合成失败", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @GetMapping("/health")

    public ResponseEntity<String> checkHealth() {
        boolean isHealthy = ttsClient.isHealthy();
        return ResponseEntity.ok(isHealthy ? "OK" : "UNAVAILABLE");
    }

    @GetMapping("/voices")

    public ResponseEntity<String[]> getSupportedVoices() {
        return ResponseEntity.ok(ttsClient.getSupportedVoices());
    }

    @GetMapping("/languages")

    public ResponseEntity<String[]> getSupportedLanguages() {
        return ResponseEntity.ok(ttsClient.getSupportedLanguages());
    }
}